
package ar.republicagroup.gestion.view;

import ar.republicagroup.gestion.entities.Cliente;
import ar.republicagroup.gestion.entities.CuentaBanco;
import ar.republicagroup.gestion.entities.Deposito;
import ar.republicagroup.gestion.entities.Usuario;
import ar.republicagroup.gestion.services.ClienteServices;
import ar.republicagroup.gestion.services.CuentaBancoServices;
import ar.republicagroup.gestion.services.DepositoServices;
import ar.republicagroup.gestion.util.JComboBoxModel;
import ar.republicagroup.gestion.util.SpringUtils;
import ar.republicagroup.gestion.util.UserSession;
import ar.republicagroup.gestion.util.helpers.UserInterfaceHelper;
import ar.republicagroup.gestion.util.messages.UIMessages;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import java.math.BigDecimal;
import java.util.Date;
import javax.swing.JOptionPane;


public class frmAddDepositoEfectivo extends javax.swing.JFrame {

   /* Services */
   ClienteServices clienteServices           = (ClienteServices)SpringUtils.getBean("clienteServices");
   CuentaBancoServices cuentaBancoServices   = (CuentaBancoServices)SpringUtils.getBean("cuentaBancoServices"); 
   DepositoServices    depositoServices      = (DepositoServices)SpringUtils.getBean("depositoServices");
   private static frmAddDepositoEfectivo instance;
   Cliente cliente;
   
    private frmAddDepositoEfectivo() {
        initComponents();
        valoresPorDefecto();
        cargarCombos();
    }
    
    public static frmAddDepositoEfectivo getInstance(){
        if(instance==null){
            instance = new frmAddDepositoEfectivo();
        }
        
        return instance;
    }

   
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        comboCliente = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        txtImporte = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtComision = new javax.swing.JTextField();
        btnRegistrar = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        comboCuentas = new javax.swing.JComboBox();
        btnCancelar = new javax.swing.JButton();
        btnActualizar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Registro de depósito"));

        jLabel2.setText("Cliente");

        comboCliente.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                comboClienteItemStateChanged(evt);
            }
        });

        jLabel1.setText("Importe");

        txtImporte.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtImporteKeyPressed(evt);
            }
        });

        jLabel3.setText("Comisión");

        txtComision.setEditable(false);

        btnRegistrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/add.png"))); // NOI18N
        btnRegistrar.setText("Registrar");
        btnRegistrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRegistrarActionPerformed(evt);
            }
        });

        jLabel4.setText("Cuenta");

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/cancel.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnActualizar.setText("jButton1");
        btnActualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnActualizarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel3)
                        .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(comboCliente, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(txtImporte)
                    .addComponent(comboCuentas, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(txtComision, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(btnActualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(btnRegistrar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnCancelar, btnRegistrar});

        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtComision, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnActualizar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(comboCuentas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtImporte, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnRegistrar)
                    .addComponent(btnCancelar))
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnRegistrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegistrarActionPerformed
            if(esValidoElFormulario()){
                registrarDeposito();
            }        
    }//GEN-LAST:event_btnRegistrarActionPerformed

    private void comboClienteItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_comboClienteItemStateChanged
        
        if(evt.getStateChange() == ItemEvent.SELECTED){
            if(comboCliente.getSelectedIndex() != 0){
                JComboBoxModel model    =(JComboBoxModel)comboCliente.getSelectedItem();
                cliente         = clienteServices.get(Integer.parseInt(model.getValue()));
                
                if(cliente.getComisionDeposito().doubleValue() > 0){
                    txtComision.setText(String.valueOf(cliente.getComisionDeposito().doubleValue()));
                } else{
                    JOptionPane.showMessageDialog(this, "El cliente no tiene asignado una comisión de depósito. Actualice sus datos.", "RGroup", JOptionPane.INFORMATION_MESSAGE); 
                    modalPanelEditCliente panelEditCliente = new modalPanelEditCliente(this, true);
                    panelEditCliente.setId_cliente(Integer.parseInt(model.getValue()));
                    panelEditCliente.setFromAnotherFrame(true);
                    UserInterfaceHelper.centreWindow(panelEditCliente);
                    panelEditCliente.setVisible(true);
                }
            }else{
                 limpiarFormulario();   
            }
        }
    }//GEN-LAST:event_comboClienteItemStateChanged

    private void btnActualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnActualizarActionPerformed
        cliente = clienteServices.get(cliente.getId());
        txtComision.setText(String.valueOf(cliente.getComisionDeposito().doubleValue()));    
    }//GEN-LAST:event_btnActualizarActionPerformed

    private void txtImporteKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtImporteKeyPressed
        if(evt.getKeyCode( ) == KeyEvent.VK_ENTER){
            if(esValidoElFormulario()){
                registrarDeposito();
            }
        }
    }//GEN-LAST:event_txtImporteKeyPressed

    private boolean esValidoElFormulario(){
        
        System.out.println("comboCliente.getSelectedIndex(): "+comboCliente.getSelectedIndex());
        
        if(comboCliente.getSelectedIndex() == 0){
            JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("requiredSelectedCliente"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.ERROR_MESSAGE);
            comboCliente.requestFocus();
            return false;
        }
        
        return true;
    }
    
    private void registrarDeposito(){
        Deposito depositoBean =  new Deposito();
        depositoBean.setClienteId(cliente);
        depositoBean.setFechaDeposito(new Date());
        depositoBean.setEfectivoDepositado(BigDecimal.valueOf(Double.parseDouble(txtImporte.getText())));
        depositoBean.setComision(BigDecimal.valueOf(Double.parseDouble(txtComision.getText())));
        depositoBean.setUsuarioId(new Usuario(UserSession.getInstance().getUser_id()));
        depositoBean.setEstado(1);
        
        /*Obtenemos la cuenta del combobox 'comboCuentas'*/
        JComboBoxModel comboModel   = (JComboBoxModel)comboCuentas.getSelectedItem();
        CuentaBanco cuentabanco     = cuentaBancoServices.get(Integer.parseInt(comboModel.getValue()));
        depositoBean.setCuentaBancoId(cuentabanco);
        String mensaje              = depositoServices.insert(depositoBean);
        
         if(mensaje !=  null){
            JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("onCompleteInsert"), UIMessages.getInfoMessage("defaultInfoTitle"), JOptionPane.INFORMATION_MESSAGE);
            int resp = JOptionPane.showConfirmDialog(this, UIMessages.getQuestionMessage("register_another_deposito"), UIMessages.getQuestionMessage("register_another_title"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                if (resp == 0){
                    limpiarFormulario(); 
                    }else{
                    dispose();
                    }
            } else{
                JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("onInsertError"),UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
            }
         
    }
    
    
    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        frmDepositoEfectivo.btnActualizar.doClick();
    }//GEN-LAST:event_formWindowClosed

   
    
    private void limpiarFormulario(){
        txtComision.setText("");
        txtImporte.setText("");
        comboCliente.setSelectedIndex(0);
        comboCuentas.setSelectedIndex(0);
        comboCliente.requestFocus();
    }
    
    
    private void valoresPorDefecto(){
         UserInterfaceHelper.setJFrameIconImage(this);
         UserInterfaceHelper.centreWindow(this);
         UserInterfaceHelper.setTitleToThisJFrame(this, "Depósito en efectivo");
         btnActualizar.setVisible(false);             
    }
    
    private void cargarCombos(){
        comboCliente.setModel(clienteServices.combo());
        comboCuentas.setModel(cuentaBancoServices.combo());
    }
    
   
    
    public static void actualizarDatosDelCliente(){
          
    }
    
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frmAddDepositoEfectivo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frmAddDepositoEfectivo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frmAddDepositoEfectivo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmAddDepositoEfectivo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmAddDepositoEfectivo().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    protected static javax.swing.JButton btnActualizar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnRegistrar;
    private javax.swing.JComboBox comboCliente;
    private javax.swing.JComboBox comboCuentas;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField txtComision;
    private javax.swing.JTextField txtImporte;
    // End of variables declaration//GEN-END:variables
}
